package com.five.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.five.dto.*;
import com.five.entity.*;
import com.five.mapper.*;
import com.five.service.UsersService;
import com.five.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
* @author 86158
* @description 针对表【users(系统用户)】的数据库操作Service实现
* @createDate 2024-07-23 21:53:56
*/
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users>
    implements UsersService{
    @Autowired
    private UsersMapper usersMapper;



    @Autowired
    private PayLogsMapper payLogsMapper;

    @Autowired
    private MembersMapper membersMapper;

    @Autowired
    private ApplyLogsMapper applyLogsMapper;

    @Autowired
    private ActiveLogsMapper activeLogsMapper;
    /**
     * 登录的业务逻辑
     * @param userLoginDto
     * @return
     */
    @Override
    public SaResult login(UserLoginDto userLoginDto) {
        //根据页面传递的账号去数据库中查询
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",userLoginDto.getUserName());
        Users user = usersMapper.selectOne(queryWrapper);
        //先判断账号是否正确，如果不正确就提示账号错误
        if(Objects.isNull(user)){//user为null,说明数据库的表中没有这个账号，提示账号错误
            return SaResult.error("账号错误！");
        }else {//user不为null,说明账号正确，判断密码
            boolean checkpw = BCrypt.checkpw(userLoginDto.getUserPassword(), user.getPassWord());
//            System.out.println(checkpw);
            if(checkpw){//true：密码正确
                //将satoken取出返回到客户端
                StpUtil.login(user.getId());
                String tokenValue = StpUtil.getTokenValue();
                return SaResult.get(200,"登录成功！",tokenValue);
            }else {//false：密码错误
                return SaResult.error("密码错误！");
            }
        }
    }

    @Override
    public SaResult queryUserInfo(String userName) {
        QueryWrapper<Users> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_name",userName);
        Users users=usersMapper.selectOne(queryWrapper);
        return SaResult.get(200,"查询成功",users);
    }


    @Override
    @Transactional(readOnly = false,propagation = Propagation.REQUIRED)
    public SaResult register(UserRegisterDto userRegisterDto) {
        Users user = new Users();
        user.setUserName(userRegisterDto.getUserName());
        //密码加密后再存入数据库中
        String pw_hash = BCrypt.hashpw(userRegisterDto.getUserPassWord(), BCrypt.gensalt(12));
        boolean checkpw = BCrypt.checkpw(userRegisterDto.getUserPassWord(),pw_hash);
        user.setPassWord(pw_hash);
        int age = Integer.parseInt(userRegisterDto.getAge());
        user.setAge(age);
        user.setGender(userRegisterDto.getGender());
        user.setAddress(userRegisterDto.getAddress());
        user.setName(userRegisterDto.getName());
        user.setPhone(userRegisterDto.getPhone());
        user.setType(userRegisterDto.getType());
        user.setStatus(userRegisterDto.getStatus());
        user.setId(String.valueOf(new Date().getTime()));
        user.setCreateTime(new Date().toLocaleString());
        int insert = usersMapper.insert(user);
        return SaResult.ok("注册成功！");
    }

    @Override
    public SaResult checkUserPwd(UserPasswordDto userPasswordDto) {
        Users user = usersMapper.selectById((String)StpUtil.getLoginId());
        boolean checkpw = BCrypt.checkpw(userPasswordDto.getOldPwd(), user.getPassWord());
        if(checkpw){
            return SaResult.ok("密码正确！");
        }else {
            return SaResult.error("密码错误！");
        }
    }

    @Override
    public SaResult updateUserPwd(UserPasswordDto userPasswordDto) {
        //加密
        String pw_hash = BCrypt.hashpw(userPasswordDto.getNewPwd(), BCrypt.gensalt(12));
        Users users=new Users();
        users.setPassWord(pw_hash);
        UpdateWrapper<Users> usersUpdateWrapper = new UpdateWrapper<>();
        usersUpdateWrapper.eq("id",StpUtil.getLoginId());
        usersMapper.update(users,usersUpdateWrapper);
        return SaResult.ok("密码修改成功");
    }

    @Override
    public SaResult updateUserInfo(UserUpdateDto userUpdateDto) {
        Users users=new Users();
        users.setUserName(userUpdateDto.getUserName());
        users.setName(userUpdateDto.getName());
        users.setGender(userUpdateDto.getGender());
        users.setPhone(userUpdateDto.getPhone());
        users.setAddress(userUpdateDto.getAddress());
        users.setAge(userUpdateDto.getAge());
        UpdateWrapper<Users> usersUpdateWrapper = new UpdateWrapper<>();
        usersUpdateWrapper.eq("id",StpUtil.getLoginId());
        usersMapper.update(users,usersUpdateWrapper);
        return SaResult.ok("信息修改成功");
    }

    @Override
    public SaResult checkUserName(UserRegisterDto userRegisterDto) {
        //全表查询
        List<Users> users = usersMapper.selectAll();
//        System.out.println(users);
        for(int i=0;i<users.size();i++){
            if(users.get(i).getUserName().equals(userRegisterDto.getUserName())){
                return SaResult.error("用户名重复");
            }
        }
        return SaResult.ok("用户名查询成功");
    }
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public SaResult deleteUser(String id) {
        // 首先检查用户是否存在
        Users user = usersMapper.selectById(id);
        if (user == null) {
            return SaResult.error("用户不存在，删除失败！");
        }
        // 级联删除相关表中的记录
        cascadeDeleteUserData(id);
        // 删除用户
        usersMapper.deleteById(id);
        return SaResult.ok("用户删除成功！");
    }
    private void cascadeDeleteUserData(String userId) {
        // 删除pay_logs表中的记录
        QueryWrapper<PayLogs> payLogsQueryWrapper = new QueryWrapper<>();
        payLogsQueryWrapper.eq("user_id", userId);
        payLogsMapper.delete(payLogsQueryWrapper);

        // 删除members表中的记录
        QueryWrapper<Members> membersQueryWrapper = new QueryWrapper<>();
        membersQueryWrapper.eq("user_id", userId);
        membersMapper.delete(membersQueryWrapper);

        // 删除apply_logs表中的记录
        QueryWrapper<ApplyLogs> applyLogsQueryWrapper = new QueryWrapper<>();
        applyLogsQueryWrapper.eq("user_id", userId);
        applyLogsMapper.delete(applyLogsQueryWrapper);

        // 删除active_logs表中的记录
        QueryWrapper<ActiveLogs> activeLogsQueryWrapper = new QueryWrapper<>();
        activeLogsQueryWrapper.eq("user_id", userId);
        activeLogsMapper.delete(activeLogsQueryWrapper);
    }

    private List<UserVo> paginateList(List<Users> usersList, Integer currentPage, Integer pageSize) {
        int startIndex = (currentPage - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, usersList.size());
        return convertToUserVoList(usersList.subList(startIndex, endIndex));
    }
    private List<UserVo> convertToUserVoList(List<Users> usersList) {
        List<UserVo> userVos = new ArrayList<>();
        for (Users user : usersList) {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            userVos.add(userVo);
        }
        return userVos;
    }
    @Override
    public List<UserVo> getAllUsers(Integer currentPage, Integer pageSize, String name) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        if (name != null && !name.trim().isEmpty()) {
            queryWrapper.like("name", name);
        }
        List<Users> usersList = usersMapper.selectList(queryWrapper);
        return paginateList(usersList, currentPage, pageSize);
    }

    @Override
    public Long countAllUsers(String name) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        if (name != null && !name.trim().isEmpty()) {
            queryWrapper.like("name", name);
        }
        return usersMapper.selectCount(queryWrapper); // 使用 MyBatis Plus 的方法获取总用户数
    }

    @Override
    public List<UserVo> getUserByName(String name) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name); // 使用like进行模糊查询
        List<Users> usersList = usersMapper.selectList(queryWrapper);
        List<UserVo> userVos = new ArrayList<>();
        for (Users user : usersList) {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            userVos.add(userVo);
        }
        return userVos;
    }

    private String generateUniqueId() {
        // 生成13位ID：时间戳后9位 + 4位随机数
        long timestamp = System.currentTimeMillis() % 1000000000L;
        int randomNum = new Random().nextInt(10000);
        return String.format("%09d%04d", timestamp, randomNum);
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public SaResult addUser(UserDto userDto) {
        Users user = new Users();
        user.setId(generateUniqueId());
        user.setUserName(userDto.getUserName());
        user.setPassWord(BCrypt.hashpw(userDto.getPassWord(), BCrypt.gensalt(12)));
        user.setName(userDto.getName());
        user.setGender(userDto.getGender());
        user.setAge(userDto.getAge());
        user.setPhone(userDto.getPhone());
        user.setAddress(userDto.getAddress());
        user.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        user.setStatus(1);
        user.setType(userDto.getType()); // 根据传入的 type 字段设置

        usersMapper.insert(user);
        return SaResult.ok("用户添加成功！");
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public SaResult deleteUsers(String[] userIds) {
        for (String id : userIds) {
            cascadeDeleteUserData(id);
        }
        usersMapper.deleteBatchIds(Arrays.asList(userIds));
        return SaResult.ok("批量删除成功！");
    }

    @Override
    public SaResult updateUser(UserDto userDto) {
        Users user = usersMapper.selectById(userDto.getId());
        if (user == null) {
            return SaResult.error("用户不存在！");
        }
        BeanUtils.copyProperties(userDto, user, "passWord");
        // 如果密码字段不为空，进行重置
        if (userDto.getPassWord() != null && !userDto.getPassWord().isEmpty()) {
            user.setPassWord(BCrypt.hashpw(userDto.getPassWord()));
        }
        usersMapper.updateById(user);
        return SaResult.ok("用户更新成功！");
    }

    //查询社团管理员id
    @Override
    public SaResult querymanagerIdsInfo() {
        List<Users> managerids = usersMapper.selectManagerIds();

        return SaResult.get(200,"查询成功！",managerids);
    }

}




